﻿using ServiceStack.OrmLite.SqlServer;
using STHPMS1.Common.C_Entity.Stmpms1;
using STHPMS1.DAL.D_Core;
using STHPMS1.ICore.I_DAL.Repository;
using STHPMS1.ICore.I_Entity.Stmpms1;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq.Expressions;
using ServiceStack.OrmLite;

namespace STHPMS1.DAL.D_Repository
{
    public class Dm_ModelgroupRepository : DalBase, IDm_ModelgroupRepository
    {
        public DataTable GetAllModelGroups(string where)
        {
            string sql =string.Format(@"
select a.*,b.PERFYEAR from DM_MODELGROUP a left JOIN
(SELECT MODELGROUP_ID,max(PERFYEAR) as PERFYEAR from DM_HISTPERF GROUP BY MODELGROUP_ID )b
on a.MODELGROUP_ID=b.MODELGROUP_ID {0} ;",where);

            return this.Adapter.DataAdapter.FillDataTable(sql);
        }


        public IDm_Modelgroup GetModelById(string id)
        {
            Dm_Modelgroup model = null;
            if (this.Scene.IsOpen)
            {
                model = this.Adapter.SingleById<Dm_Modelgroup>(id);
            }
            else
            {
                model = this.Adapter.OpenDbConnection().SingleById<Dm_Modelgroup>(id);
                this.Adapter.CloseConnection();       
            }
           
            return model;
        }

        public double? GetSegEsalByYear(string segid,int year)
        {
            double? easl = null;

            if (this.Scene.IsOpen)
            {
                easl = this.Adapter.Scalar<Dm_Esalage, double?>(f => f.Easl, p => p.Segid == segid && p.Perfyear == year);
            }
            else
            {
                easl = this.Adapter.OpenDbConnection().Scalar<Dm_Esalage, double?>(f => f.Easl, p => p.Segid == segid && p.Perfyear == year);
                this.Adapter.CloseConnection();
            }

            return easl;
        
        }        
    }
}
